/*
 * @Author: DaTree
 * @Date: 2020-11-18 13:06:23
 * @LastEditTime: 2021-06-02 15:27:37
 * @LastEditors: DaTree
 * @Description: DaTreeEdit
 * @FilePath: \services\src\controller\socket\socket-hub.js
 * @天将降大任于是人也，必先苦其心志，劳其筋骨，饿其体肤，空乏其身，行拂乱其所为。 ——《孟子•告子下》
 * @symbol_custom_string_obkoro1_copyright: Copyright ${now_year} DaTree
 */
import config from '../../config/index'
import control from './socket-control'
export default class SocketHub {
  constructor(server) {
    // let server = require('http').createServer(app)
    // let io = require('socket.io')(server)
    const io = require('socket.io')({
      path: '/websocket',
      serveClient: false,
    });
    // const server = require('http').createServer();

    io.attach(server, {
      pingInterval: 10000,
      pingTimeout: 5000,
      cookie: false
    });

    // app.use('/', express.static(__dirname + '/public'));
    // const cors = require('cors');
    // // const whitelist = ['http://localhost:8080', 'http://example2.com'];
    // const corsOptions = {
    //   credentials: true, // This is important.
    //   origin: (origin, callback) => {
    //     // console.log(origin)
    //     // if (whitelist.includes(origin))
    //     return callback(null, true)

    //     // callback(new Error('Not allowed by CORS'));
    //   }
    // }
    // app.use(cors(corsOptions));
    // io
    // server.listen({
    //   host: '127.0.0.1',
    //   port: config.socketPort
    // }, function () {
    //   console.log('websocket running on ' + config.socketPort)
    // })
    //socket部分
    io.on('connection', function (socket) {
      console.log(`已连接:${socket.id}`)
      for (let eventKey in control.module) {
        //接收并处理客户端的hi事件
        // control.moduleName
        socket.on(`${control.moduleName}_${eventKey}`, function (data) {
          // console.log(data); 接收客户端数据
          control.module[eventKey](data, (result) => {
            //触发客户端事件 
            socket.emit(`${control.moduleName}_${eventKey}`, result)
          })
        })
      }
      //断开事件
      socket.on('disconnect', function (data) {
        console.log(`断开:${socket.id}`)
        // socket.emit('c_leave', '离开');
        //socket.broadcast用于向整个网络广播(除自己之外)
        //socket.broadcast.emit('c_leave','某某人离开了')
      })
    })
  }
}
